import axios from 'axios'
import { getToken, removeToken } from './cookie'
import { IMessage } from './message'
import { ApiCode } from '@/enums/ApiCode'
import jsonBigint from 'json-bigint'
import router from '@/router'
import { useAppStore } from '@/store/modules/app'
import { ViewLogin } from '@/enums'
import qs from 'qs'

const instance = axios.create({
    baseURL: import.meta.env.VITE_APP_URL,
    timeout: 10000,
    transformResponse: data => {
        const json = jsonBigint({ storeAsString: true })
        return json.parse(data)
    }
})

instance.interceptors.request.use( config => {
    const token = getToken()
    if(token !== null){
        config.headers['Authorization'] = `Bearer ${token}`
        config.headers['Accept-Language'] = useAppStore().language
        config.paramsSerializer = params => {
            return qs.stringify(params, { indices: false })
        }
    }
    return config
},error => {
    console.error(error)
    return error
})

instance.interceptors.response.use(response => {
    const result = response.data
    if(result.code === ApiCode.UN_AUTHENTICATION){
        removeToken()
        router.push({ path: ViewLogin.Path })
        IMessage({ content: 'token已经过期，请重新登录', type: 'error' })
    }
    return result
}, error => {
    return error
})


// instance.interceptors.response.use( async (response: AxiosResponse<ApiResult<any>, any>) => {
//     const result: ApiResult<any> = response.data

//     if(result.code === ApiCode.FAILED){
//         IMessage({ content: result.message, type: 'error' })
//     }

//     if(result.code === ApiCode.UN_AUTHENTICATION){
//         removeToken()
//         await router.push({ path: ViewLogin.Path })
//         IMessage({ content: 'token已经过期，请重新登录', type: 'error' })
//         return result
//     }

//     // if(result.code === ApiCode.ERROR){
//     //     await router.push({ path: ViewPath.Error })
//     //     IMessage({ content: result.message })
//     // }

//     return result
// }, async (error) => {
//     console.error('错误信息如下=====')
//     console.error(error)
//     return error
// })

export default instance